var ListTree = function(options){
	var opts = {
		contner 		: null,				//容器
		li_width 		: 200, 				//每个列表的宽
		li_height 		: null, 			//列表高度
		url				: null,				//获取Opts的URL
		parent 			: 'parent', 		//上级ID
		root 			: '',				//初始化parent值
		item_id 		: '_id',			//返回item的ID
		item_name 		: 'name', 			//返回item的名称（显示名称）
		children_load	: function(){},		//每项加载时执行
		item_click		: function(li){}	//每项点击后
	};
	options = $.extend(opts, options);

	var contner_h = $(options.contner).height();
	var load_children = function(ul, parent){
		$(ul).css({width:options.li_width, height:contner_h}).append('<li class="loading">正在加载</li>')
			.next('ul').remove();//删除后面的记录
		var param = {};
		param[options.parent] = parent;
		$.get(options.url, param, function(data){
			var json = toJSON(data);
			$(ul).find('.loading').remove();

			if(json.data !== null){
				for(var i in json.data){
					var item = json.data[i];
					var li = $('<li rid="' + item[options.item_id] + '">' + item[options.item_name] + '</li>')
						.appendTo(ul)
						.click(function(){
							//点击一项后
							var ul = $(this).parent('ul');
							ul.find('>li.selected').removeClass('selected');
							$(this).addClass('selected');
							var children_ul = null;
							if($(ul).next('ul').length){
								$(ul).next('ul:gt(0)').remove();
								children_ul = $(ul).next('ul');
								children_ul.html('');
							}else{
								children_ul = $('<ul></ul>');
								$(ul).after(children_ul);
							}
							var parent_id = $(this).attr('rid');
							load_children(children_ul, parent_id);
							if($.isFunction(options.item_click)){
								options.item_click(this);
							}
						});
				}
			}
			if(!ul.find('>li').length){
				ul.remove();
			}
		});
	};

	//加载根下的
	var root_ul = $('<ul></ul>').appendTo(options.contner);
	load_children(root_ul, options.root);
};

var ExtBox = function(options){
	var default_options = {
		'id' 					: 'ext_info_box',
		'parent'				: null,
		'ext_box_nav_id' 		: 'ext_box_nav',
		'ext_box_contner_id' 	: 'ext_info_contner',
		'opacity'				: 0.95,
		'items'					: []
	};
	options = $.extend(default_options, options);

	if(!$('#' + options.id).length){
		$('<div id="ext_info_box"><div id="ext_info_contner"></div><div id="ext_box_nav"></div><a id="box_close" href="javascript:void(0)" title="关闭">X</a></div>').appendTo('body');
		$('#box_close').click(function(){
			//关闭按钮
			obj.close();
		});
	}
	var box_parent 	= null;
	if(options.parent !== null){
		box_parent = $(options.parent);
	}
	
	var opened 		= false;
	var box 		= $('#' + options.id);
	var box_nav 	= $('#' + options.ext_box_nav_id);
	var box_contner = $('#' + options.ext_box_contner_id);
	var cur_handler = null;
	var CONFS 		= {};
	var obj 		= this;
	var box_left 	= 0;
	var box_top 	= 0;
	var CACHE 		= {};
	var body_scro_x = null;
	var body_scro_y = null;

	/**
	 * 初始化ExtBox
	 */
	var init = function(){
		if(box_parent !== null){
			box_left = $(box_parent).offset().left + $(box_parent).width();
			box_top = $(box_parent).offset().top;
		}
		box_left -= $(box_nav).width();

		$(box).css({left : box_left, top : box_top});

		var selected_index = -1;
		$(options.items).each(function(i){
			obj.addItem(this);
			if(typeof(this['selected']) !== 'undefined' && this.selected){
				selected_index = i;
			}
		});
		if(selected_index > -1){
			box_nav.find('a:eq(' + selected_index + ')').click();
		}
		box.css({
			opacity : options.opacity
		});

		$(document).click(function(event){
			if(!$(event.target).parents('#' + options.id).length){
				obj.close();
			}
		});
	};

	/**
	 * 添加一个获取URL的项目
	 * @param item : 项目配置，比addItem方法的多了以下几个属性:
	 * {
	 *		onload 	: function(){}, //加载完成后执行
	 * 		url 	: '',	//需要加载的链接
	 * 		cache 	: true	//是否需要缓存本地址，默认为false
	 * }
	 * @param callback : 创建项目成功后执行，注意，是创建成功后，在加载URL之前执行
	 */
	this.addUrlItem = function(item, callback){
		if($.isArray(item)){
			//如果是一个数组时，批量添加
			for(var i=0,c=item.length; i<c; ++i){
				var it = item[i];
				obj.addUrlItem(it);
			}
			if($.isFunction(callback)){
				setTimeout(function(){
					callback();
				});
			}
			return;
		}

		var onload = null;
		if(typeof(item['onload']) !== 'undefined'){
			//设置了启动项
			onload = item.onload;
		}
		if(typeof(item['id']) === 'undefined'){
			item.id = (Math.random() + '').substr(3, 5);
		}
		var cache = false;
		if(typeof(item['cache']) !== 'undefined'){
			cache = item.cache;
		}
		item.open = function(){
			var url = null;
			if($.isFunction(item.url)){
				url = item.url();
			}else{
				url = item.url;
			}
			if(cache && typeof(CACHE[url]) !== 'undefined'){
				//使用缓存内容
				$('#ext_info_contner').html(CACHE[url]);
				if($.isFunction(onload)){
					onload();
				}
				return;
			}
			$('#ext_info_contner').html('正在加载，请稍候...');
			$.get(url, function(html){
				if(cache){
					//缓存内容
					CACHE[url] = html;
				}
				$('#ext_info_contner').html(html);
				if($.isFunction(onload)){
					onload();
				}
			});
		};
		obj.addItem(item, function(){
			//obj.open(item.id);
			if($.isFunction(callback)){
				setTimeout(function(){
					callback();
				});
			}
		});
	};

	/**
	 * 添加一个项目
	 * @param item 项目配置
	 * 	{
	 *		'id' 			: 'item_id',
	 *		'title' 		: '标题',
	 *		'width' 		: 300,	//默认为100%
	 *		'height' 		: 400,	//默认为100%
	 *		'del_on_close' 	: false, //关闭后是否删除当前项目
	 *		'open' 			: function(){},
	 *		'close' 		: function(){},
	 * 		'expend' 		: false	//默认是否展开，默认为false
	 *	}
	 */
	this.addItem = function(item, callback){
		if($.isArray(item)){
			//如果是一个数组时，批量添加
			for(var i=0,c=item.length; i<c; ++i){
				var it = item[i];
				obj.addItem(it);
			}
			if($.isFunction(callback)){
				setTimeout(function(){
					callback();
				});
			}
			return;
		}

		if(typeof(item['id']) === 'undefined'){
			item.id = (Math.random() + '').substr(3, 5);
		}
		CONFS[item.id] = item;
		var li = $('<a href="javascript:void(0)" id="handler_' + item.id + '">' + item.title + '</a>')
			.click(function(){
				var handler = this;
				if(opened){
					if(cur_handler == $(handler).attr('id')){
						closeBox(handler, item);
					}else{
						//如果开着
						obj.close(null, function(){
							openBox(handler, item);
						});
					}
				}else{
					openBox(handler, item);
				}
			})
			.appendTo(box_nav);
		if(typeof(item['expend']) && item.expend){
			//需要展开
			li.click();
		}
		if($.isFunction(callback)){
			setTimeout(function(){
				callback();
			});
		}
	};

	/**
	 * 删除一个项目
	 * @param id 项目的ID
	 */
	this.removeItem = function(id, callback){
		if(typeof(CONFS[id]) == 'undefined'){
			alert('此项目不存在！');
			return;
		}
		var handler = $('#handler_' + id);
		if(cur_handler == 'handler_' + id){
			//当前显示中
			closeBox(handler, CONFS[id], function(){
				obj.removeItem(id, callback);
			});
		}else{
			$('#handler_' + id).remove();
			delete CONFS[id];
			if($.isFunction(callback)){
				callback();
			}
		}
	};

	/**
	 * 删除所有项目
	 */
	this.removeAll = function(callback){
		if(opened){
			obj.close(null, function(){
				obj.removeAll(callback);
			});
			return;
		}
		CONFS = {};
		$(box_nav).html('');
		if($.isFunction(callback)){
			callback();
		}
	}

	/**
	 * 打开Box
	 * @param handler 导航，即是打开哪个<a>的内容
	 * @param conf 配置中需要打开的item配置
	 * @param callback，打开后执行的事件，如果设置了本事件，配置中的事件将在本事件之后执行
	 */
	var openBox = function(handler, conf, callback){
		if(typeof(conf['width']) === 'undefined'){
			var parent_width = box_parent === null ? 0 : $(box_parent).width();
			conf.width = $(window).width() - parent_width - $(box_nav).width() - 22;
		}
		var box_height = 0;
		if(typeof(conf['height']) === 'undefined'){
			if(box_parent === null){
				box_height = $(window).height();
			}else{
				box_height = $(box_parent).height() - 14;
			}
			box_height -= 22;
		}else{
			box_height = conf.height;
		}
		if(box_height < $(box_nav).height() + 10){
			box_height = $(box_nav).height() + 10;
		}
		
		opened = true;
		$(handler).addClass('selected');

		box_contner.css({width : conf.width, height:box_height});

		box.css({
			left : box_left - conf.width, 
			opacity : options.opacity
		})
		.dequeue()
		.animate({
			left : box_left + 22
		}, function(){
			//处理背景body的滚动条
			body_scro_x = $('body').css('overflow-x"');
			if(body_scro_x === null)body_scro_x = 'auto';
			body_scro_y = $('body').css('overflow-y"');
			if(body_scro_y === null)body_scro_y = 'auto';
			$('body').css({"overflow-x":"hidden","overflow-y":"hidden"});
			cur_handler = $(handler).attr('id');
			if($.isFunction(callback)){
				callback();
			}
			if($.isFunction(conf['open'])){
				conf.open();
			}
		});
	};

	/**
	 * 关闭Box
	 * @param handler 导航，即是关闭哪个<a>的内容
	 * @param conf 配置中需要打开的item配置
	 * @param callback，关闭后执行的事件，如果设置了本事件，配置中的事件将在本事件之后执行
	 */
	var closeBox = function(handler, conf, callback){
		opened = false;
		cur_handler = null;
		$(box_nav).find('a.selected').removeClass('selected');
		//先关闭底部按钮
		$(box_contner).find('.bottom_buttons').remove();
		box.dequeue().animate({left : box_left - $(box_contner).width()}, function(){
			box.css({opacity:50});
			//处理背景body的滚动条
			$('body').css({'overflow-x':body_scro_x, 'overflow-y':body_scro_y});
			$('#ext_info_contner').html('');
			if($.isFunction(callback)){
				callback();
			}
			if($.isFunction(conf['close'])){
				conf.close();
			}
			if(typeof(conf['del_on_close']) && conf.del_on_close){
				//销毁项目
				obj.removeItem(conf.id);
			}
		});
	};

	/**
	 * 打开某个Box
	 * @param id 需要打开的item
	 * @param callback 打开后的事件
	 */
	this.open = function(id, callback){
		if(typeof(CONFS[id]) == 'undefined'){
			alert('此项目不存在！');
			return;
		}
		var handler = $('#handler_' + id);
		if(opened){
			if(cur_handler!=null && cur_handler == $(handler).attr('id')){
				if($.isFunction(callback)){
					callback();
				}
			}else{
				//如果开着其它的项目
				obj.close(null, function(){
					obj.open(id, callback);
				});
			}
		}else{
			openBox(handler, CONFS[id], callback);
		}
	};

	/**
	 * 关闭某个Box
	 * @param id 需要关闭的item
	 * @param callback 关闭后的事件
	 */
	this.close = function(id, callback){
		//如果没有指定id，则表示关闭当前打开的项目
		if(!opened){
			//如果已经关闭
			if($.isFunction(callback)){
				callback();
			}
			return;
		}

		if((typeof(id) == 'undefined' && cur_handler != null) || id == null){
			if(cur_handler === null)return;
			id = cur_handler.substr(8);
		}
		if(typeof(CONFS[id]) == 'undefined'){
			alert('此项目不存在！');
			return;
		}
		var handler = $('#handler_' + id);
		if(opened){
			closeBox(handler, CONFS[id], callback);
		}else{
			if($.isFunction(callback)){
				callback();
			}
		}
	};

	init();
}

$.fn.extend({
	fill_parent : function(options){
		var opts = {
			parent 	: null,
			width 	: true,
			height 	: true
			// 'on' : function(){}
		};
		if($.isFunction(options)){
			opts.on = options;
		}else{
			opts = $.extend(opts, options);
		}
		
		return this.each(function(i){
			var parent = opts.parent;
			if(parent === null){
				parent = $(this).parent();
			}
			var p_w = $(parent).width();
			var p_h = $(parent).height();
			var l = $(this).offset().left;
			var t = $(this).offset().top;
			$(this).css({width:p_w - l, height:p_h - t});
			if($.isFunction(opts.on)){
				opts.on();
			}
		});
	},

	auto_check : function(opts){
		var default_opts = {
			next_focus	: true,
			error_lock 	: true,
			checkAll 	: false,
			submit_btn 	: null,	//提交按钮，默认为不可用，onSuccess时可用
			onSuccess 	: function(form, opts){$(opts.submit_btn).removeAttr('disabled');},			//全部正常时事件
			onError 	: function(errorObj, form, opts){$(opts.submit_btn).attr('disabled', 'disabled');}	//有错误时事件
		};
		opts = $.extend(default_opts, opts);
		var on_error = function(errorObj, form){
			$(errorObj).addClass('error');
		}

		var form = null;
		var check = function(obj){
			var val = null;
			form = $(obj).parents('form');
			if($(obj).hasClass('y_selector')){
				val = $(obj).find('input').val();
			}else{
				val = $(obj).val();
			}

			var reg = $(obj).attr('rule');
				// alert(reg);
			// if(typeof(reg) === 'undefined'){
			// 	console.log(obj);
			// }
			var result = false;
			if(reg.indexOf(':') === 0){
				var validator = reg.substr(1);
				result = eval(validator + '("' + val + '")');
			}else{
				result = val.match(reg);
			}
			if (!result){
				on_error(obj, form);
				opts.onError(obj, form, opts);
				return;
			}else{
				$(obj).removeClass('error');
			}

			if(!$(form).find('.error').length){
				opts.onSuccess(form, opts);
			}
		};

		if($(this).find('[rule]:visible').length){
			var first_input = $(this).find('[rule]:visible:eq(0)').set_focus();
			check(first_input);
		}
		$(opts.submit_btn).attr('disabled', 'disabled');

		if(opts.next_focus){
			$(this).find('[next_focus]').next_focus({
				submit_btn 	: opts.submit_btn,
				error_lock 	: opts.error_lock,
				scroll 		: $(form).find('.setting_content')
			});
		}
		return this.each(function(i){
			$(this).find('[rule]').each(function(){
				if($(this).hasClass('y_selector')){
					$(this).find('input').change(function(){
						check($(this).parents('.y_selector'));
					});
					if($(this).is(':visible')){
						check(this);
					}
				}else{
					$(this).blur(function(){
						check(this);
					}).change(function(){
						check(this);
					}).keyup(function(){
						check(this);
					}).each(function(){
						if($(this).is(':visible')){
							check(this);
						}
					});
				}
			});
		});
	},

	auto_img : function(opts){
		var default_opts = {
			'onload' : function(img){}
		};
		opts = $.extend(default_opts, opts);
		var set_img_margin_top = function(img, top){
			$(img).css({'margin-top': top});//.attr('alt', top);
			if($.isFunction(opts.onload)){
				opts.onload(img, top);
			}
		};
		return this.each(function(){
			var image = this;
			var src = $(this).attr('src');
			var height = parseInt(src.replace(/^.*\/\d+x(\d+)\/.*$/, '$1'));
			var img = new Image();
			img.src = src;
			img.onload = function(){ 
				set_img_margin_top(image, (height - img.height) / 2);
				return;
			}
		});
	},

	next_focus : function(opts){
		var default_opts = {
			submit_btn 	: null,
			error_lock 	: false,
			scroll 		: 'body'
		};
		opts = $.extend(default_opts, opts);
		return this.each(function(){
			var obj = this;
			$(obj).unbind('keydown').keydown(function(event){
				var code = event.which;
				if(code != 13){
					return true;
				}
				if($(obj)[0].tagName === 'TEXTAREA' && !event.shiftKey){
					//如果是textarea时，按位SHIFT切换到下一个焦点
					return true;
				}

				//如果是回车
				if(opts.error_lock){
					if($(this).hasClass('error')){
						return false;
					}
					if($(obj).parents('form').find('.error').length){
						$(obj).parents('form').find('.error:eq(0)').set_focus({select:true});
						return false;
					}
				}
				var next_focus = $(this).attr('next_focus');
				var next_obj = null;
				var is_next = false;
				if(next_focus == ''){
					//如果没有指定，则直接使用下一个
					var form = $(obj).parents('form');
					$(form).find('[next_focus]:visible').each(function(){
						if(next_obj !== null){
							//如果选中有
							return;
						}
						if(is_next){
							next_obj = this;
							$(next_obj).set_focus({select:true});
							is_next = false;//也可以当成是否最后一个表单
							return;
						}
						if(this === obj){
							is_next = true;
						}
					});
				}else{
					next_obj = $(next_focus);
					$(next_obj).set_focus({select:true});
				}
				if(next_obj === null){
					//如果没有找到有，则尝试查找有错误的
					if($(form).find('input[type="text"].error:eq(0)').length){
						$(form).find('input[type="text"].error:eq(0)').set_focus({select:true});
					}else if(opts.submit_btn != null){
						$(opts.submit_btn).set_focus({select:true});
					}
				}
				if($(next_obj) != null){
					var t = t1 = 0;
					try{
						t1 = $(opts.scroll).offset().top;
						t = $(next_obj).offset().top - t1;
					}catch(e){}
					
					var scroll_top = $(opts.scroll).scrollTop();
					var view_height = $(opts.scroll).height();

					if(t < 0 || t > view_height){
						//在可见范围之外
						$(opts.scroll).dequeue().animate({'scrollTop': t + scroll_top});
					}
				}
				return false;
			});
		});
	},

	set_focus : function(opts){
		var default_opts = {
			select 	: false,
			value 	: false
		};
		opts = $.extend(default_opts, opts);
		return this.each(function(){
			if(opts.value !== false){
				$(this).val(opts.value);
			}
			var input = this;
			setTimeout(function(){
				if(opts.select){
					$(input).select().focus();
				}else{
					$(input).focus();
				}
			}, 100);
		});
	},

	ajax_form : function(opts){
		var default_opts = {
			'submit_btn' 		: '.submit',
			'is_alert' 			: true,
			'dataType'			: 'json',
			'info_show_time' 	: 3,
			'form_position' 	: 'relative',
			'before_submit' 	: function(form){},
			'on_error' 			: function(form, data){},
			'success' 			: function(form, data){
				var return_url = $(form).attr('url');
				//成功
				if(return_url!=null && return_url!=''){
					window.location.href = return_url;//刷新界面
				}else{
					window.location.reload();
				}
			},
			'error' : function(form, e){
				$(form).find('.info').html('发生错误，请重试！').show();
				setTimeout(function(){
					$(form).find('.info').fadeOut();
				},1000 * opts.info_show_time);
			}
		};
		opts = $.extend(default_opts, opts);
		return this.each(function(i){
			var ajax_form = $(this);
			if(ajax_form.hasClass('inited'))return;
			if(ajax_form.css('position') != 'absolute'){	
				if(opts.form_position != null){
					ajax_form.css({position : opts.form_position});
				}
			}
			var busy = false;
			var options = {
				dataType : opts.dataType,
				success : function(data){
					busy = false;
					if(opts.dataType === 'text'){
						opts.success(ajax_form, data);
						return;
					}
					ajax_form.find('.info').html(data.info);
					if(opts.is_alert){
						alert(data.info);
					}
					if(data.result){
						//成功
						opts.success(ajax_form, data.data);
					}else{
						//失败
						ajax_form.find('.info').html(data.info).show();
						opts.on_error(ajax_form, data);
					}
					setTimeout(function(){
						ajax_form.find('.info').fadeOut();
					},1000 * opts.info_show_time);
				},
				error : function(form, e){
					busy =false;
					opts.error(form, e);
				}
			};
			options.form = this;
			if(opts.url){
				options.url = opts.url;
			}
			ajax_form.ajaxForm(options).addClass('inited');

			var info_box = $('<div class="info ui-state-highlight ui-corner-all"></div>').hide().css({position:'absolute',top:0,right:0}).appendTo(ajax_form);
			ajax_form.find(opts.submit_btn).click(function(){
				if(busy){
					alert('系统繁忙，请稍候再试！');
					return;
				}
				busy = true;
				if(opts.before_submit){
					if(opts.before_submit(ajax_form)===false){
						busy = false;
						return false;
					}
				}
				info_box.html('正在提交，请稍候...').show();
				ajax_form.submit();
				if($(this).attr('type') == 'submit'){
					return false;
				}
			});
		});
	},

	magnifier : function(options){
		options = $.extend({
			
		}, options);

		var VARS = {};

		var init = function(img){
			if(VARS.inited)return;
			VARS.inited = true;
			var src = '/themes/' + THEME + '/images/magnifier_bg.png';
			var main_image_content = VARS.CONTNER.find('.main_image');
			main_image_content.append('<div class="magnifier_bg"></div><div class="magnifier_body"></div>');

			var src = img.attr('src');
			src = src.replace(/\/\d+x\d+\//, '/');

			var selected_li = VARS.CONTNER.find('.img_nav .selected');

			//获取原始图片规格
			VARS.w = parseInt(selected_li.attr('w'));
			VARS.h = parseInt(selected_li.attr('h'));
			if(VARS.w <= 350 && VARS.h <= 350){
				//图片过小，显示大图
				exit();
			}

			//获取当前图片规格
			VARS.image_w = $(img).width();
			VARS.image_h = $(img).height();

			VARS.image_l = $(img).offset().left;
			VARS.image_t = $(img).offset().top;
			VARS.image_m_t = parseInt($(img).css('margin-top'));
			VARS.image_m_l = (main_image_content.width() - VARS.image_w) / 2;

			//获取图片展示器总大小
			var image_contner = main_image_content.parent();
			VARS.image_contner_width = image_contner.width();
			VARS.image_contner_height = image_contner.height();
			var big_img_width = 1000 - VARS.image_contner_width;
			VARS.CONTNER.find('.magnifier_body').css({
				width : big_img_width,
				height : VARS.image_contner_height - 2,
				right : -big_img_width-2,
				background: 'white url(' + src + ') no-repeat'
			});

			//计算拖动框规格
			// VARS.rate = VARS.w / VARS.image_w;
			VARS.b_w = VARS.image_w * VARS.image_contner_width / VARS.w;
			VARS.b_h = VARS.image_h * VARS.image_contner_height / VARS.h;
			// document.title = VARS.image_l + ',' + VARS.image_t;
			VARS.CONTNER.find('.magnifier_bg')
				.css({width:VARS.b_w, height:VARS.b_h});

			VARS.scrollTop = $(document).scrollTop();
		};

		var exit = function(img){
			VARS.inited = false;
			VARS.CONTNER.find('.magnifier_bg,.magnifier_body').remove();
		};

		var move = function(img, x, y){
			var fix_t = VARS.image_t - VARS.image_m_t - VARS.scrollTop;
			var fix_l = VARS.image_l - VARS.image_m_l;
			var l = Math.round(x - VARS.b_w / 2 - fix_l);
			var t = Math.round(y - VARS.b_h / 2 - fix_t);
			if(l < VARS.image_m_l){
				l = VARS.image_m_l;
			}else if(l > VARS.image_w - VARS.b_w + VARS.image_m_l + 2){
				l = VARS.image_w - VARS.b_w + VARS.image_m_l + 2;
			}
			if(t < VARS.image_m_t){
				t = VARS.image_m_t;
			}else if(t > VARS.image_h - VARS.b_w + VARS.image_m_t + 6){
				t = VARS.image_h - VARS.b_w + VARS.image_m_t + 6;
			}
			show_big_img(l - VARS.image_m_l, t - VARS.image_m_t);
			VARS.CONTNER.find('.magnifier_bg').css({top:t,left:l});
		};

		var show_big_img = function(x, y){
			var left = VARS.w / VARS.image_w * x;
			var top = VARS.h / VARS.image_h * y;
			VARS.CONTNER.find('.magnifier_body').css({
				'background-position' : '-' + left + 'px -' + top + 'px'
			});
		};

		$(document).scroll(function(){
			if(!VARS.inited)return;
			VARS.scrollTop = $(this).scrollTop();
		});

		var slide = function(index){
			if(VARS.scroll)return;
			if(index<0)return;
			if(index + 4 > VARS.item_count)return;
			VARS.scroll = true;
			if(VARS.slide_index < index){
				VARS.CONTNER.find('.img_nav ul>li:eq(' + (index - 1) + ')').dequeue().animate({'margin-top':-82}, function(){VARS.scroll=false;VARS.slide_index = index;});
			}else{
				VARS.CONTNER.find('.img_nav ul>li:eq(' + (index) + ')').dequeue().animate({'margin-top':0}, function(){VARS.scroll=false;VARS.slide_index = index;});
			}
		};

		return this.each(function(i){
			VARS.scroll = false;
			VARS.CONTNER = $(this);
			
			var img = $(this).find('.main_image>img');
			$(this).find('img').auto_img();
			if(VARS.CONTNER.find('.no_picture').length){
				return;
			}
			VARS.CONTNER.find('.main_image>img')
				.mouseover(function(event){
					VARS.x = event.clientX;
					VARS.y = event.clientY;
					init(img);
				});
			$(this).find('.prev_btn').click(function(){
				slide(VARS.slide_index + 1);
			});
			$(this).find('.next_btn').click(function(){
				slide(VARS.slide_index - 1);
			});
			VARS.slide_index = 0;
			VARS.item_count = $(this).find('.img_nav>ul>li').length;
			$(this).find('.img_nav>ul').mousewheel(function(event, delta) {
				if(Math.abs(delta) < 0.2)return false;
				if(delta > 0){
					slide(VARS.slide_index - 1);
				}else{
					slide(VARS.slide_index + 1);
				}
				return false;
			});
			$(this).find('.img_nav>ul>li').click(function(){
				if($(this).hasClass('selected'))return;
				VARS.CONTNER.find('.img_nav>ul>li.selected').removeClass('selected');
				$(this).addClass('selected');
				var src = $(this).find('img').attr('src');
				src = src.replace(/\/\d+x\d+\//, '/350x350/');
				VARS.CONTNER.find('.main_image>img').attr('src', src).auto_img();
				var index = $(this).index();
				if(index - VARS.slide_index == 3){
					slide(VARS.slide_index + 1);
				}else if(index == VARS.slide_index){
					slide(VARS.slide_index - 1);
				}
			});
			$(document).mousemove(function(event){
				if(!VARS.inited)return;
				var x = event.clientX;
				var y = event.clientY;
				var fix_t = VARS.scrollTop;
				if(x > VARS.image_l && x < VARS.image_l + VARS.image_w && y > VARS.image_t - fix_t && y < VARS.image_t + VARS.image_h - fix_t){
					move(img, x, y);
				}else{
					exit(img);
				}					
			});
		});
	},

	y_setting : function(options){
		options = $.extend({
			ext_btn 		: null,
			back_btn		: null,
			ext_content		: null, //扩展栏
			before_ext		: function(ext_btn, options){return true;},
			before_return 	: function(ext_btn, prev_btn, options){return true;},
			on_ext 			: function(ext_btn, options){},
			on_back 		: function(ext_btn, prev_btn, options){}
		}, options);
		var setting_auto_size = function(options){
			var setting_offset = $('.setting_form').offset();
			var SETTING_TOP = setting_offset.top;
			var setting_height = W_H - SETTING_TOP;
			var buttons_height = 0;
			if($('.setting_form .buttons').length){
				buttons_height = $('.setting_form .buttons').height();
			}
			$('.setting_form').find('.setting_nav').height(setting_height);

			//减掉底部的按钮栏高度
			setting_height -= buttons_height;
			$('.setting_form').find('.setting_content').height(setting_height);

			//保证最后一个选项可以拉到顶
			var last_dd = $('.setting_form .setting_content dd:last').removeAttr('style');
			var last_dd_height = last_dd.height();
			var last_dd_top = last_dd.offset().top;
			var last_dt_top = $('.setting_form .setting_content dt:last').offset().top;
			var last_group_height = last_dd_top - last_dt_top + last_dd_height;
			if(last_group_height < setting_height){
				last_dd.height(setting_height + last_dt_top - last_dd_top);
			}

			if(options.ext_content != null){
				var ext_content = $(options.ext_content);
				ext_content.css({height:setting_height + buttons_height,top:SETTING_TOP + 1})
					.find(options.back_btn).css({top:(setting_height + buttons_height - 57)/2});

				ext_content.find('>.ext_main_body').css({height:setting_height + buttons_height - 80});
			}
			
		};

		var scroll_busy = false;
		var init_y_setting = function(obj, options){
			$(obj).parent().css({'overflow':'hidden'});
			var scrollItems = [];
			$(obj).find('.setting_content dt').each(function(index){
				$(this).prev('dd:eq(0)').addClass('last_dd');
				var item = $('<div class="item_title" index="' + index + '">' + $(this).text() + '</div>').click(function(){
					if(scroll_busy)return;
					scroll_busy = true;
					var t = parseInt($('.setting_content dt:eq(' + index + ')').offset().top)
						+ parseInt($('.setting_content').scrollTop()) - 32;
					$(obj).find('.setting_content').dequeue().animate({'scrollTop':t}, function(){
						scroll_busy = false;
					});
					selecteItem(obj, this);
				});
				$(obj).find('.setting_nav').append(item);
			});
			$(obj).find('.setting_nav>.item_title:eq(0)').addClass('selected');
			$(obj).find('.setting_content').css({'overflow-x':'hidden'}).scroll(function(){
				if(scroll_busy)return;
				var item_index = null;
				var h = $(obj).find('.setting_content').height();
				$(obj).find('.setting_content>dt').each(function(i){					
					var item_top = $(this).offset().top;
					if(item_top - 80 < 0){
						item_index = i;
					}
				});
				selecteItem(obj, $('.setting_nav>.item_title:eq(' + item_index + ')'));
			});
			$(obj).find('.setting_nav').mousewheel(function(event, delta) {
				if(scroll_busy || Math.abs(delta) < 0.2)return false;
				if(delta > 0){
					if($(obj).find('.setting_nav .item_title.selected').prev('.item_title').length){
						$(obj).find('.setting_nav .item_title.selected').prev('.item_title:eq(0)').click();
					}
				}else{
					if($(obj).find('.setting_nav .item_title.selected').next('.item_title').length){
						$(obj).find('.setting_nav .item_title.selected').next('.item_title:eq(0)').click();
					}
				}
			});

			if(options.ext_btn !== null){
				//点击进入扩展项按钮
				// alert('.setting_content ' + options.ext_btn);
				$(document).on('click', options.ext_btn, function(event){
					var ext_btn = event.target;
					if(!options.before_ext(ext_btn, options)){
						return;
					}
					$(ext_btn).addClass('setting_exted');
					$(options.ext_content).show().dequeue().animate({left:'20%'});
					$('.setting_content').dequeue().animate({'margin-left':'-80%'});
					if($.isFunction(options.on_ext)){
						options.on_ext(ext_btn, options);
					}
				});
				$(document).on('click', options.back_btn, function(event){
					var back_btn = event.target;
					if(!options.before_back(ext_btn, back_btn, options)){
						return;
					}
					$(options.ext_content).dequeue().animate({left:'100%'});
					$('.setting_content').dequeue().animate({'margin-left':'0%'});
					if($.isFunction(options.on_back)){
						var ext_btn = $('.setting_content ' + options.ext_btn + '.setting_exted').removeClass('setting_exted');
						options.on_back(ext_btn, back_btn, options);
					}
				});
			}
			
		};

		function selecteItem(obj, item){
			$(obj).find('.setting_nav .selected').removeClass('selected');
			$(item).addClass('selected');
		}

		return this.each(function(i){
			init_y_setting(this, options);

			//注册窗口resize事件并执行
			addWinResize(function(){
				setting_auto_size(options);
			}, true);
		});
	}, 

	y_datepicker : function(options){
		options = $.extend({
			dateFormat : 'yy-mm-dd',
			monthNames : ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
			dayNamesMin : [ '日','一', '二', '三', '四', '五', '六']
		}, options);
		return this.each(function(){
			$(this).datepicker(options);
		});
	},

	uploader : function(options){
		options = $.extend({
			on_complete : function(img_id, data){}
		}, options);
		return this.each(function(i){
			var holder = this;
			var img_id = null;
			if(typeof($(this).attr('id')) === 'undefined'){
				img_id = 'img_' + gen_id();
				$(this).attr('id', img_id);
			}else{
				img_id = $(this).attr('id');
			}
			$('#' + img_id).uploadify({
				formData : {
					timestamp		: 1383824760,
					token			: '0facca869aa3db5a204d927ebf65d845'
				},
				buttonImage			: '/images/uploader.png',
				width 				: 104,
				height 				: 28,
				mutil 				: false,
				// queueID 			: "queue_ad_uploader",
				swf 				: "/js/jquery_plus/uploadify/uploadify.swf",
				uploader 			: "/manage/site/upload",
				/**
				 * data : json_encode(array(
					'url' 		=> $info['url'],
					'name' 		=> $info['name'],
					'title' 	=> $info['title'],
					'original' 	=> $info['originalName'],
					'state' 	=> $info['state']
				));
				 */
				onUploadSuccess 	: function(file, data, response){
					data = eval('(' + data + ')');
					if(data.state != 'SUCCESS'){
						//发生错误
						alert(data.state);
						return;
					}

					if($.isFunction(options.on_complete)){
						options.on_complete(img_id, data);
					}
				}
			});
		});
	},

	mousewheel: function(up, down, preventDefault) {
		return this.hover(
			function() {
				$.event.mousewheel.giveFocus(this, up, down, preventDefault);
			},function() {
				$.event.mousewheel.removeFocus(this);
			}
		);
	},
	mousewheeldown: function(fn, preventDefault) {
		return this.mousewheel(function(){}, fn, preventDefault);
	},
	mousewheelup: function(fn, preventDefault) {
		return this.mousewheel(fn, function(){}, preventDefault);
	},
	unmousewheel: function() {
		return this.each(function() {
			$(this).unmouseover().unmouseout();
			$.event.mousewheel.removeFocus(this);
		});
	},
	unmousewheeldown : $.fn.unmousewheel,
	unmousewheelup : $.fn.unmousewheel
});

$.event.mousewheel = {
	giveFocus: function(el, up, down, preventDefault) {
		if (el._handleMousewheel) $(el).unmousewheel();
		 
		if (preventDefault == window.undefined && down && down.constructor != Function) {
			preventDefault = down;
			down = null;
		}
		 
		el._handleMousewheel = function(event) {
			if (!event) event = window.event;
			if (preventDefault)
				if (event.preventDefault) event.preventDefault();
				else event.returnValue = false;
			var delta = 0;
			if (event.wheelDelta) {
				delta = event.wheelDelta/120;
				if (window.opera) delta = -delta;
			} else if (event.detail) {
				delta = -event.detail/3;
			}
			if (up && (delta > 0 || !down))
				up.apply(el, [event, delta]);
			else if (down && delta < 0)
				down.apply(el, [event, delta]);
		};
		 
		if (window.addEventListener)
			window.addEventListener('DOMMouseScroll', el._handleMousewheel, false);
		window.onmousewheel = document.onmousewheel = el._handleMousewheel;
	},
	 
	removeFocus: function(el) {
		if (!el._handleMousewheel) return;
		 
		if (window.removeEventListener)
			window.removeEventListener('DOMMouseScroll', el._handleMousewheel, false);
		window.onmousewheel = document.onmousewheel = null;
		el._handleMousewheel = null;
	}
};

function toJSON(data){
	return eval('(' + data + ')');
}

var W_W = W_H = 0;
var WIN_RESIZE = [];
/**
 * 注册一个窗口重置大小事件
 */
function addWinResize(fun, run_now){
	WIN_RESIZE = $(WIN_RESIZE).add(fun);
	if(typeof(run_now) !== 'undefined' && run_now){
		fun();
	}
}

/**
 * y_selector type=text 时的弹出执行方法
 */
function y_selector_text_on_show(target, callback){
	var api = $(target).qtip('api');
	var content = api.elements.content;
	var input = $(content).find('input[name="select_text"]');
	var ok = $(content).find('.selector_ok_btn')
	ok.click(function(){
		var val = input.val();
		$(target).find('>input').val(val).trigger('change');
		if(val == ''){
			val = $(target).find('>span').attr('title');
		}
		$(target).find('>span').html(val);
		api.hide();

		if($.isFunction(callback)){
			callback(target, val);
		}
	});

	$(content).find('.select_options>span').click(function(){
		input.val($(this).text());
		setTimeout(function(){
			input.select().focus();
		});
	}).dblclick(function(){
		$(this).click();
		setTimeout(function(){
			ok.click();
		});
	});
	setTimeout(function(){
		input.select().focus();
	}, 200);
}

function gen_id(){
	var id = Math.random() + '';
	return id.substr(3, 7);
}

$(function(){
	addWinResize(function(){
		W_W = $(window).width();
		W_H = $(window).height();
	}, true);
	$(window).resize(function(){
		$(WIN_RESIZE).each(function(){
			if($.isFunction(this)){
				this();
			}
		});
	});
});
